﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Plugin;
using PluginInterface;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Policy;
using System.Threading.Tasks;
using WalkingTec.Mvvm.Core;

namespace IoTGateway.Controllers
{

    /// <summary>
    /// 基于Http的调用方法
    /// </summary>
    [Public]
    [Route("HttpRpc")]
    public class HttpRpcController : Controller
    {
        private readonly DeviceService _deviceService;
        private readonly MessageService _messageService;

        public HttpRpcController(DeviceService deviceService,MessageService messageService)
        {
            _deviceService = deviceService;
            _messageService = messageService;

            
        }
        [AllowAnonymous]
        [Public]
        [ActionDescription("修改设备数据")]
        [HttpPost("InvokeRpc")]
        public async Task<IActionResult> InvokeRpc([FromBody] RpcRequest data)
        {
            var dv = _deviceService.DeviceThreads.Where(q => q.Driver is IHttpDriver && q.Driver.DeviceId == data.DeviceName).ToList();

            if (!dv.Any())
            {   
                return BadRequest("没有对应的处理驱动");
            }

            var v = dv.First();
            var hv = v.Driver as IDriver;

            v.ExcHttpRpc(data);

            return Json(new { code = 200,message = "成功" });

        }

        [AllowAnonymous]
        [Public]
        [ActionDescription("查询设备数据")]
        [HttpPost("GetDeviceData")]
        public async Task<IActionResult> GetDeviceData([FromBody] GetDeviceDataRequest data)
        {   
            var deviceName = data.name;
            var handler = _messageService.PlatformHandler;
            if (handler == null) { 
                return NotFound();
            }
            var dic = handler.DeviceData;
            if (dic == null || !dic.ContainsKey(deviceName)) {
                return NotFound();
            }
            var deviceData = dic[deviceName];

            return Json(deviceData);
        }


        [AllowAnonymous]
        [Public]
        [ActionDescription("下载数据到PLC")]
        [HttpPost("InvokeDownload/{site}")]
        public async Task<IActionResult> InvokeDownload([FromRoute] string site)
        {
            return await Invoke(site, false);
        }

        [AllowAnonymous]
        [Public]
        [ActionDescription("PLC上传PLC数据")]
        [HttpPost("InvokeUpload/{site}")]
        public async Task<IActionResult> InvokeUpload([FromRoute] string site)
        {   
            return await Invoke(site,true);
        }


        async Task<IActionResult> Invoke(string site, bool isUpload)
        {
            Request.EnableBuffering();
            string inputData = "";
            Request.Body.Position = 0;
            using (var reader = new StreamReader(Request.Body))
            {
                inputData = await reader.ReadToEndAsync();
            }

            var dv = _deviceService.DeviceThreads.Where(q => q.Driver is IHttpDriver && q.Driver.DeviceId == site).ToList();

            if (!dv.Any())
            {
                return BadRequest("没有对应的处理驱动");
            }

            var v = dv.First();

            var hv = v.Driver as IHttpDriver;
            var result = string.Empty;
            var startTime = DateTime.Now;

            if (isUpload)
                result = await hv.PostUploadUrl(inputData,site);
            else
                result = await hv.PostDownloadUrl(inputData, site);
            var endTime = DateTime.Now;

            
            if (!string.IsNullOrWhiteSpace(result))
            {
                
                v.SaveClientRpcLog(startTime,endTime,isUpload ? "upload" : "download", inputData, true,result);
                return Content(result, "application/json");
            }
            else
            {
                v.SaveClientRpcLog(startTime, endTime, isUpload ? "upload" : "download", inputData, false, result);

                return BadRequest("请求异常");
            }
        }





    }

    public class GetDeviceDataRequest { 
        public string name {  get; set; }
    }
}
